package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.exception.BusinessException;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired(required = false)
    private EmployeeMapper employeeMapper;

    @Override
    public R<Employee> login(Employee employee) {
        String userMD5 = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        employee.setPassword(userMD5);
        Employee login = employeeMapper.login(employee);

        if (login == null) {
            return R.error("账号或密码错误");
        }
        if (login.getStatus() == 0) {
            return R.error("账号已被禁用,请联系管理员");
        }
        return R.success(login);
    }

    @Override
    public void save(Employee employee) {
        Employee byUsername = employeeMapper.findByUsername(employee);
        if (byUsername != null) {
            throw new BusinessException("用户名已存在");
        }
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        LocalDateTime now = LocalDateTime.now();
        employee.setCreateTime(now);
        employee.setUpdateTime(now);
        employee.setStatus(1);
        employeeMapper.save(employee);
    }

    @Override
    public Page<Employee> findByName(Integer page, Integer pageSize, String name) {
        PageHelper.startPage(page, pageSize);
        List<Employee> employeeList = employeeMapper.findByName(name);
        PageInfo<Employee> pageInfo = new PageInfo<>(employeeList);
        Page<Employee> employeePage = new Page<>(pageInfo.getList(), pageInfo.getTotal(), pageInfo.getPageSize(), pageInfo.getPageNum());
        return employeePage;
    }

    @Override
    public void update(Employee employee) {
        employee.setUpdateTime(LocalDateTime.now());
        employeeMapper.update(employee);
    }

    @Override
    public Employee findById(Integer id) {
        Employee employee = employeeMapper.findById(id);
        return employee;
    }
}
